import globalMitt from '../../utils/globalMitt.js';
import {
  wxRequest
} from '../../utils/server';
const _wxRequest = new wxRequest();

const app = getApp()
Component({

  properties: {
    video: String,
    modelName: String,
    className: String
  },

  data: {
    imgUrl: app.globalData.imgUrl,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    duration: 0,
    percent: 0,
    maxDuration: 59
  },

  lifetimes: {
    // 在组件实例进入页面节点树时执行
    attached: function () {
      const _this = this
      wx.getSystemInfo({
        success: function (res) {
          if (res.platform != "ios") {
            _wxRequest.wxTonkenAjax({
              url: app.globalData.apiUrl + '/sys/protected/comm/beanCrud/sys.DictVO/find',
              method: 'POST',
              data: {
                groupCode: "1-sys-ntf-videoLimit",
                pageSize: 5,
              },
              loading: false
            }, (res) => {
              if (res.list && res.list.length > 0) {
                _this.setData({ maxDuration: res.list[0].val })
              }
            })
          } else {
            _this.setData({ maxDuration: 59 })
          }
        }
      })

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },


  methods: {

    playVideo (e) {
      let src = e.currentTarget.dataset.src
      console.log(src, 'src')
      if (src)
        this.startVideoPlayer(src)
      else
        wx.showToast({
          title: '没有找到视频路径',
          icon: 'none',
        })
    },

    startVideoPlayer (src) {
      this.setData({
        videoSrc: src,
      }, () => {
        wx.showLoading({
          title: '加载视频中'
        })
      })
    },

    onVideoPlay () {
      console.log('开始播放')
      wx.hideLoading()
    },

    onVideoEnded () {
      console.log('结束播放')
      wx.hideLoading()
    },

    onVideoFullscreenchange (e) {
      if (!e.detail.fullScreen) {
        this.videoPlayerContext.stop()
      }
      wx.hideTabBar({
        aniamtion: false
      })
    },

    onVideoError (e) {
      console.log(e, '播放失败')
      wx.hideLoading()
      wx.showToast({
        title: `播放失败:${e.detail.errMsg}`,
        icon: 'none'
      })
    },



    addVideo () {
      // 这里有几个需求
      // 1.时间不超过10秒
      // 2.能够从手机相册选取也能视频拍摄
      // 3.拍摄的时候提示现在拍摄了几秒
      // 4.超过时长要像app一样自动停止提示
      const that = this
      wx.showActionSheet({
        itemList: ['从相册上传', '从相机拍摄'],
        success: function (res) {
          if (res.tapIndex === 0) {
            console.log(res)
            const maxDuration = that.data.maxDuration
            wx.chooseVideo({
              sourceType: ['album', 'camera'],
              maxDuration: maxDuration,
              // compressed:false,
              camera: 'back',
              success: (res) => {
                if (res.duration > maxDuration) {
                  wx.showModal({
                    title: '视频时长不能大于60秒',
                    showCancel: false,
                  })
                  return
                }

                var duration = Math.floor(res.duration);
                if (res.duration > 1 && res.duration < 10) {
                  duration = '0' + duration
                }

                that.setData({
                  duration: duration
                })



                console.log(duration, 'duration')

                const videoPath = res.tempFilePath
                that.uploadVideo({ videoPath })


              }
            })
          } else {
            wx.navigateTo({
              url: '/pages/publish/camera/camera',
            })
            var onTakeVideo = function (res) {
              const videoPath = res.tempVideoPath
              const thumbPath = res.tempThumbPath
              that.uploadVideo({ videoPath, thumbPath })
              globalMitt.off('takeVideo', onTakeVideo)
            }
            globalMitt.on('takeVideo', onTakeVideo)
          }

        },
      })
    },


    uploadVideo (res) {
      wx.showLoading({
        title: '上传视频中',
        mask: true
      })
      // 上传视频并使用返回的路径作为视频的路径
      const uploadTask = wx.uploadFile({
        //url: app.globalData.apiUrl + '/' + this.data.modelName + '/protected/comm/file/'+this.data.className+'/fileUpload',
        url: app.globalData.apiUrl + '/com/comm/oss/upload',
        header: {
          "Authorization": wx.getStorageSync('Authorization'),
        },
        formData: {
          subfolder: 'video'
        },
        filePath: res.videoPath,
        name: 'file',
        success: (response) => {
          console.log('上传视频', response)
          if (response.statusCode == 200) {
            var data = JSON.parse(response.data) //后台返回的是字符串，转成对象格式
            if (data.success) {
              console.log('上传视频结果', data)
              var relativeFilePath = data.datas.data.url;
              this.setData({
                video: relativeFilePath
              })
              this.triggerEvent("videoCallback");//触发回调
            }

            wx.hideLoading()
          } else {
            wx.showToast({
              icon: 'none',
              title: '视频上传失败',
            })
          }
        },
        fail: (res) => {
          wx.showToast({
            icon: 'none',
            title: '视频上传失败',
          })
        }
      })
      uploadTask.onProgressUpdate((res) => {
        //console.log('上传进度', res.progress)
        this.setData({ percent: res.progress })
        //console.log('已经上传的数据长度', res.totalBytesSent)
        //console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      })
    },

    deleteVideo () {
      this.setData({
        video: null,
        percent: 0
      })
      this.triggerEvent("videoCallback");//触发回调
    },








  }
})